import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:ts_app_dart/utils/index.dart';

const Duration duraVal = Duration(milliseconds: 2500);

class HomeWillPop extends StatefulWidget {
  final Widget child;
  final Duration duration;

  const HomeWillPop({
    Key key,
    this.child,
    this.duration = duraVal,
  }) : super(key: key);

  @override
  _HomeWillPopState createState() => _HomeWillPopState();
}

class _HomeWillPopState extends State<HomeWillPop> {
  DateTime _lastTime;

  Future<bool> onWillPop() async {
    DateTime now = DateTime.now();
    if (_lastTime == null || now.difference(_lastTime) > widget.duration) {
      _lastTime = DateTime.now();
      Fluttertoast.showToast(msg: '再次点击退出应用', fontSize: 16.0);
      return Future.value(false);
    }

    Fluttertoast.cancel();
    CommonUtils.exitApp(context);
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onWillPop,
      child: widget.child,
    );
  }
}
